package edu.scu.sculijobs.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@SuppressWarnings("serial")
public class SaveNotificationSettings extends BaseServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		System.out.println("Creating new setting ");
		resp.setContentType("text/html");
		PrintWriter out = resp.getWriter();
		out.println("<HTML><BODY>");

		saveSetting(req);
		out.println("Settings saved!");

		out.println("</BODY></HTML>");
	    resp.setStatus(HttpServletResponse.SC_OK);
	}

	private void saveSetting(HttpServletRequest req) {
		String userName = checkNull(req.getParameter("userid"), "userid");
		String liToken = checkNull(req.getParameter("litoken"), "litoken");
		String liTokenSecret = checkNull(req.getParameter("litokensecret"), "litokensecret");
		String jobtitle = checkNull(req.getParameter("jobtitle"), "jobtitle");
		String companies = checkNull(req.getParameter("companies"), "companies");
		String zipcode = checkNull(req.getParameter("zipcode"), "zipcode");
		String deviceid = checkNull(req.getParameter("deviceid"), "deviceid");

		List<NotificationSettings> notificationSettings = Dao.INSTANCE.getNotificationSettingss(userName);
		if (notificationSettings.isEmpty()) {
			Dao.INSTANCE.add(userName, liToken, liTokenSecret,
					jobtitle, companies, zipcode, deviceid);
		} else {
			NotificationSettings update = notificationSettings.get(0);
			update.setLiToken(liToken);
			update.setLiTokenSecret(liTokenSecret);
			update.setJobtitle(jobtitle);
			update.setCompanies(companies);
		
			
			update.setZipcode(zipcode);
			update.setDeviceid(deviceid);
		    EntityManager em = EMFService.get().createEntityManager();
		    em.persist(update);
		    em.close();
		}
	}

	private String checkNull(String s, String paramName) 
	{
		if (s == null) {
			throw new IllegalArgumentException(paramName + " cannot be null");
		}
		return s;
	}
}
